package com.weiiew.backend.executor;

import com.weiiew.backend.entity.KeyInfo;
import com.weiiew.backend.entity.config.KeyConfig;
import com.weiiew.backend.entity.enums.LogState;
import com.weiiew.backend.exception.ExecutorParamsException;
import com.weiiew.backend.operation.CombinedKeyClick;
import com.weiiew.backend.operation.DelayOperation;
import com.weiiew.backend.operationUtils.OperationSequence;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @Description 键盘操作执行器
 * @Author 魏锴
 * @Date 2025/4/28
 */
@Slf4j
@Component
public class KeyboardExecutor extends baseExecutor<KeyConfig> {
    @Override
    protected void initResource(KeyConfig config) throws ExecutorParamsException {
        executor.setOperations(getSequence(config));
        executor.setTerminationPolicy(config.getPolicy());
        executor.setLogger(messagingTemplate, config.getChannel());
        executor.setLogState(LogState.SEQUENCE);
    }

    @Override
    protected void clearResource() {
    }

    public OperationSequence getSequence(KeyConfig config) throws ExecutorParamsException {
        OperationSequence sequence = new OperationSequence();
        long time = 0;
        if (config.getList().isEmpty()) throw new ExecutorParamsException("按键序列不能为空");
        for (KeyInfo info : config.getList()) {
            if (info.getKeyCode() == null) throw new ExecutorParamsException("按键序列中存在未知按键");
            sequence.addOperation(new CombinedKeyClick(info, time));
            time += info.getDuration() + info.getInterval();
        }
        sequence.addOperation(new DelayOperation((int) time)); // 防止只有一个操作时快速运行
        return sequence;
    }
}
